package com.ff.compare.controller;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.ff.compare.enity.ReturnDTO;
import com.ff.compare.service.CompareService;

@RestController
public class CompareController {
	
	@Autowired
	private CompareService compareService;

	@RequestMapping("compareByExcel")
	public ReturnDTO compareByExcel(MultipartFile file,HttpServletResponse response) throws IOException{
		InputStream inputStream = file.getInputStream();
		List<String> productNameList = analysisExcel(inputStream);
		List<String> errorProductNameList = compareService.compareByExcel(productNameList);
		//需要的话也可返还excel文件以供下载
		return new ReturnDTO(errorProductNameList);
	}
	
    public List<String> analysisExcel(InputStream inputStream){
        List<String> productNameList= new ArrayList<>();
        try {
            Workbook workbook = WorkbookFactory.create(inputStream); 
            //遍历第一个Sheet
            for (int s = 0; s < 1; s++) {
                Sheet sheet = workbook.getSheetAt(s);
                //获取总行数
                int rowCount = sheet.getPhysicalNumberOfRows(); 
                //遍历第二行开始
                for (int r = 1; r < rowCount; r++) {
                    Row row = sheet.getRow(r);
                    if(row == null){
                        return productNameList;
                    }
                    //遍历第二列开始
                    for (int c = 1; c < 2; c++) {
                        Cell cell = row.getCell(c);
                        int cellType = cell.getCellType();
                        if(cell != null && Cell.CELL_TYPE_STRING == cellType){
                        	productNameList.add(cell.getStringCellValue());
                        }
                        cell=null;
                    }
                    row=null;
                }
                workbook.close();
                inputStream.close();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return productNameList;
    }
	
}
